﻿@inject IPeopleService peopleService
@inject IUserStatusService statusService

<MudDialog>
    <TitleContent>
        <MudText Typo="Typo.h6">Add Name </MudText>
    </TitleContent>
    <DialogContent>
        @if( saving )
        {
            <ProgressSpinner ProgressText="Updating name...."/>
        }
        else
        {
            <MudTextField @bind-Value="@NewName" Immediate="true" DebounceInterval="250" OnBlur="CheckForMerge"/>
            @if( ! string.IsNullOrEmpty(NewName) )
            {
                <PeopleGrid SearchText="@NewName" ExcludeSelectedPersonId="@theObject.PersonId" PersonState="Person.PersonState.Identified"
                            OnPersonClicked="SelectPerson" Small="true" Disabled="true" ShowNotFoundMessage="false"/>
            }

            @if( showDupeMessage )
            {
                <div class="merge-message">
                    There is already an entry for '@NewName'. By selecting that Name, you will
                    merge/add this face to that person.
                </div>
            }
        }
    </DialogContent>
    <DialogActions>
        <MudButton OnClick="Cancel" Disabled="@saving">Cancel</MudButton>
        @if( showDupeMessage )
        {
            <MudButton Color="Color.Primary" ButtonType="MudBlazor.ButtonType.Submit"
                       OnClick="Merge" Disabled="@saving">
                Merge with @NewName
            </MudButton>
        }
        else
        {
            <MudButton Color="Color.Primary" ButtonType="MudBlazor.ButtonType.Submit"
                       OnClick="Save" Disabled="@saving">
                Save as @NewName
            </MudButton>
        }
    </DialogActions>
</MudDialog>

@code {

    [CascadingParameter] MudDialogInstance MudDialog { get; set; }

    [Parameter] public ImageObject theObject { get; set; }

    private string NewName { get; set; }
    private bool showDupeMessage = false;
    private bool saving = false;

    protected override void OnInitialized()
    {
        if( theObject.Person != null && theObject.Person.Name != null )
        {
            NewName = theObject.Person.Name;
        }
    }

    private async Task SelectPerson( Person person )
    {
        NewName = person.Name;

        await CheckForMerge();
    }
    
    private async Task CheckForMerge()
    {
        if( NewName != "Unknown" )
        {
            var req = new PeopleRequest { SearchText = NewName, State = Person.PersonState.Identified, Count = 100, Start = 0 };
            var matches = await peopleService.GetPeople(req);

            // First, check if the name is the same as somebody else in the system. 
            var match = matches.FirstOrDefault(x => x.Name.Equals(NewName, StringComparison.OrdinalIgnoreCase) && x.PersonId != theObject.PersonId);
            var showDupe = match != null;
            
            if( showDupeMessage != showDupe )
            {
                showDupeMessage = showDupe;
                StateHasChanged();
            }
        }
    }

    private async Task Save()
    {
        await UpdateName();
    }

    private async Task UpdateName( bool merge = false)
    {
        try
        {
            saving = true;
            StateHasChanged();
            var req = new NameChangeRequest { ImageObjectId = theObject.ImageObjectId, PersonId = theObject.PersonId, NewName = NewName, Merge = merge};
            await peopleService.UpdatePersonName(req);

            if(merge)
                statusService.UpdateStatus($"Face merged with '{NewName}'");
            else
                statusService.UpdateStatus($"Name saved as '{NewName}'");
        }
        finally
        {
            saving = false;
        }

        MudDialog.Close(DialogResult.Ok(true));
    }

    private async Task Merge()
    {
        await UpdateName(true);
    }

    private void Cancel()
    {
        MudDialog.Close(DialogResult.Cancel());
    }

}